package com.qk.management.aop;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.qk.common.enums.ParamEnum;
import com.qk.common.exception.CommonException;
import com.qk.management.aop.anno.Cacheable;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * author：zzq
 * createTime：2025/10/18 09:19
 * description： 
 */
@Aspect
@Component
@Slf4j
@SuppressWarnings("all")
public class CacheableAspect {
    @Autowired
    private StringRedisTemplate redisClient;

    //定义切点
    @Pointcut("@annotation(com.qk.management.aop.anno.Cacheable)")
    public void pt() {
    }

    //定义通知
    @Around("pt()")
    public Object cacheable(ProceedingJoinPoint pjp) throws NoSuchMethodException {
        Object returnValue = null;
        Cacheable annotation = null;
        String key = null;
        try {
            //获取缓存的key = 前缀+方法名
            Class<?> targetClass = pjp.getTarget().getClass();
            String name = pjp.getSignature().getName();
            Method method = targetClass.getMethod(name);
            annotation = method.getAnnotation(Cacheable.class);
            key = annotation.keyPrefix() + name;
            //获取缓存
            String jsonStr = redisClient.opsForValue().get(key);
            if (ObjectUtil.isNotEmpty(jsonStr)) {
                return JSONUtil.toBean(jsonStr, method.getReturnType());
            }
        } catch (Exception e) {
            log.error("缓存异常", e.getMessage());
        }
        //缓存未命中
        try {
            returnValue = pjp.proceed();
        } catch (Throwable e) {
            returnValue = "操作有问题,稍后重试!";
            //抛出异常直接返回给全局异常处理器
            CommonException.throwCommonException(ParamEnum.OPERATING_ERROR);
        }
        //数据加入缓存
        try {
            redisClient.opsForValue().set(key, JSONUtil.toJsonStr(returnValue), annotation.expireTime(), annotation.expireTimeUnit());
        } catch (Exception e) {
            log.error("缓存存入异常", e.getMessage());
        }
        return returnValue;
    }
}
